// cloudfunctions/toggleProductWant/index.js
const cloud = require('wx-server-sdk');
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
    try {
        const {
            productId,
            productName,
            productImage,
            userId
        } = event;

        // 验证参数
        if (!productId || !userId) {
            return {
                success: false,
                message: '缺少必要参数'
            };
        }

        // 查询用户是否已经想要该产品
        const wantResult = await db.collection('user_wants')
            .where({
                userId,
                productId,
                status: 'active'
            })
            .get();

        const isWanted = wantResult.data.length > 0;

        if (isWanted) {
            // 已想要，取消想要
            await db.collection('user_wants').doc(wantResult.data[0]._id).update({
                data: {
                    status: 'deleted',
                    updateTime: db.serverDate()
                }
            });

            // 减少产品想要数
            await db.collection('blindbox_products').where({
                productId: productId
            }).update({
                data: {
                    wantCount: _.inc(-1)
                }
            });

            return {
                success: true,
                isWanted: false,
                message: '取消想要成功'
            };
        } else {
            // 未想要，添加想要
            const result = await db.collection('user_wants').add({
                data: {
                    userId,
                    productId,
                    productName,
                    productImage,
                    createTime: db.serverDate(),
                    updateTime: db.serverDate(),
                    status: 'active'
                }
            });

            // 增加产品想要数
            await db.collection('blindbox_products').where({
                productId: productId
            }).update({
                data: {
                    wantCount: _.inc(1)
                }
            });

            return {
                success: true,
                isWanted: true,
                wantId: result._id,
                message: '想要成功'
            };
        }
    } catch (error) {
        console.error('切换想要状态失败', error);
        return {
            success: false,
            message: error.message || '服务器错误',
            error: error.message
        };
    }
};